package geektime.ioc;

import com.google.inject.*;

import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Guice基本使用的示例
 */
public class GuiceDemo {

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @interface Message {}

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @interface Count{}

    static class DemoModule extends AbstractModule {

        @Provides
        @Count
        static Integer providerCount() {
            return 3;
        }

        @Provides
        @Message
        static String provideMessage() {
            return "Hello World";
        }
    }

    static class Greeter {
        private String message;
        private Integer count;

        @Inject
        public Greeter(@Message String message, @Count Integer count) {
            this.message = message;
            this.count = count;
        }

        void sayHello() {
            for (int i = 0; i < count; i++) {
                System.out.println(message);
            }
        }
    }

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new DemoModule());
        Greeter greeter = injector.getInstance(Greeter.class);
        greeter.sayHello();
    }
}
